package com.aqie.appletserver.service.impl;

import com.aqie.appletserver.service.IUploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class UploadService implements IUploadService {
    private static String lineSeparator = System.getProperty("line.separator"); // File.separator

    private final String fileName = "file";

    /** 上传文件保存路径 */
    @Value("${file.localUploadPath}")
    private String FILE_SAVE_PATH ; // "D:/upload/"

    // 访问的目录
    @Value("${file.staticUploadPath}")
    private String STATIC_UPLOAD_PATH; // "/upload/"

    @Value("${file.serverUrl}")
    private String SERVER_URL;      // http://192.168.0.9:8080


    @Override
    public Map<String,String> uploadFile(HttpServletRequest request) throws Exception {
        // log.info("文件上传开始" + lineSeparator);
        Map<String,String> res = new HashMap<>();
        // 1.获取从前台传过来得文件
        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = req.getFile(fileName);

        // 2.获得文件扩展名
        String extOfFile = getExtOfFile(multipartFile);
        // 3.保存到本地
        BufferedOutputStream bos = null;
        String filename = null;
        try {
            File dir = new File(FILE_SAVE_PATH);
            if (!dir.exists()) {// 判断文件目录是否存在
                dir.mkdirs();
            }
            filename = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + (int) (Math.random() * 1000) + "."
                    + extOfFile;
            bos = new BufferedOutputStream(new FileOutputStream(FILE_SAVE_PATH + filename));
            bos.write(multipartFile.getBytes());
            res.put("localSavePath",FILE_SAVE_PATH + filename);
            res.put("databaseSavePath",STATIC_UPLOAD_PATH + filename);
            res.put("fileName",filename);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            log.info("访问路径：{}", SERVER_URL + STATIC_UPLOAD_PATH + filename);
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return res;
    }

    @Override
    public Map<String,String> uploadAudio(HttpServletRequest request, MultipartFile files) {
        Map<String,String> res = new HashMap<>();
        // 如果目录不存在就创建
        File uploadDir = new File(FILE_SAVE_PATH);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        // 获取文件的 名称.扩展名
        String oldName = files.getOriginalFilename();
        String extensionName = "";
        // 获取原来的扩展名
        if ((oldName != null) && (oldName.length() > 0)) {
            int dot = oldName.lastIndexOf('.');
            if ((dot > -1) && (dot < (oldName.length() - 1))) {
                extensionName = oldName.substring(dot);
            }
        }
        // 构建文件名称
        String fileName = System.currentTimeMillis() + "_" + System.nanoTime()
                + extensionName;
        // 获取
        String[] fileType = { ".M4A",".CD", ".WAVE", ".AIFF", ".AU", ".MPEG", ".MP3",
                ".MPEG-4", ".MIDI", ".WMA", ".RealAudio", ".VQF", ".OGGVORBIS",
                ".AMR" };
        List<String> fileTyepLists = Arrays.asList(fileType);
        if(fileTyepLists.contains(extensionName.toUpperCase())){
            // -----如果是音频文件的话
            // 构建本地文件路径
            String filePath = FILE_SAVE_PATH + fileName;
            // 保存文件
            try {
                FileUtils.writeByteArrayToFile(new File(filePath),
                        files.getBytes());
                res.put("localSavePath",filePath);
                res.put("databaseSavePath",STATIC_UPLOAD_PATH + fileName);
                res.put("fileName",fileName);
                return res;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }else {
            log.info("不是音频文件");
            return null;
        }


    }

    private String getExtOfFile(MultipartFile multipartFile) {
        // 获取文件的 名称.扩展名
        String oldName = multipartFile.getOriginalFilename();
        String extensionName = "";
        // 获取原来的扩展名
        if ((oldName != null) && (oldName.length() > 0)) {
            int dot = oldName.lastIndexOf('.');
            if ((dot > -1) && (dot < (oldName.length() - 1))) {
                extensionName = oldName.substring(dot+1);
            }
        }
        return extensionName;
    }
}
